package com.zjdiepu.www.manage.api.system;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.lang.ZNode;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.ibiz.system.ISysAppMenuService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.response.Nemu;
import com.zjdiepu.www.model.system.dto.SysAppMenu;
import com.zjdiepu.www.model.system.ext.SysAppMenuExt;

/**
 * sys_app_菜单Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年10月30日 17时22分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "appMenu", produces="application/json;charset=UTF-8")
@Api(tags = {"sys_app_菜单"}, produces="application/json;charset=UTF-8")
public class SysAppMenuController extends BaseController {
    @Resource
    private ISysAppMenuService sysAppMenuService;
    
    /**
	 * 权限树形结构
	 * @author xiongxiaotun
	 * @date 2017年3月21日
	 * @since v1.0.0
	 * @param powerExt
	 * @return
	 */
	@RequestMapping(value = { "queryTree" }, method = { RequestMethod.POST })
	public ApiResponse queryTree(String roleId) {
		if(StringUtils.isBlank(roleId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY.getCode(), "请选择角色");
		}
		List<SysAppMenu> sysAppMenus = sysAppMenuService.selectByRoleId(null);
		
		List<SysAppMenu> userSysAppMenus = sysAppMenuService.selectByRoleId(roleId);
		
		final Set<String> hasPowers = CollectionUtils.isEmpty(userSysAppMenus) ? new HashSet<>() : userSysAppMenus.stream().map(userPower -> userPower.getId()).collect(Collectors.toSet());
		
		List<ZNode>  znodes = new ArrayList<ZNode>();
		if(CollectionUtils.isNotEmpty(sysAppMenus)) {
			znodes = sysAppMenus.stream().map(sysAppMenu -> new ZNode(sysAppMenu.getId(), sysAppMenu.getParentId(), sysAppMenu.getMenuCode(), sysAppMenu.getMenuName(), true, hasPowers.contains(sysAppMenu.getId()))).collect(Collectors.toList());
		}
		return ApiResponse.success(znodes);
	}
    
    /**
	 * @author xiongxiaotun <br/>
	 * @Title: getNemus  <br/>
	 * @Description: 菜单列表 <br/>
	 * @param powerCode
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getNemus", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getNemus(String powerCode) {
		SysUser currentUser =(SysUser)getCurrentUser();
		Map<String, List<Nemu>> map = CollectionInitUtil.emptyMap();
		Map<String, List<Nemu>> userNemus = currentUser.getNemus();
		if(null != userNemus) {
			List<Nemu> top = userNemus.get("top");
			map.put("top", top);
			if(StringUtils.isBlank(powerCode)) {
				Nemu nemu = top.get(0);
				powerCode = nemu.getPowerCode();
			}
			List<Nemu> nemus = userNemus.get(powerCode);
			map.put("nemus", nemus);
		}
		return ApiResponse.success(map);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getPowerList  <br/>
	 * @Description: 查询所有菜单权限 <br/>
	 * @param sysAppMenuExt
	 * @return
	 * @version V1.0  <br/>
	 */
	@RequestMapping(value="getPowerList", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResponse getPowerList(@ModelAttribute SysAppMenuExt sysAppMenuExt) {
		sysAppMenuExt.notDeleted();
		sysAppMenuExt.withOutPage();
		sysAppMenuExt.setOrderSql("`SORT_VALUE` ASC");
		List<SysAppMenu> result = sysAppMenuService.selectByExt(sysAppMenuExt);
		return ApiResponse.success(result);
	}

    /**
     * @author xiongxiaotun <br/>
     * @Title: add  <br/>
     * @Description: 新增sys_app_菜单 <br/>
     * @param sysAppMenu
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增sys_app_菜单", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ApiResponse add(@Validated(Add.class) @ModelAttribute SysAppMenu sysAppMenu) {
    	AbstractSysUser currentUser = getCurrentUser();
		SysAppMenu sysPowerParam = new SysAppMenu();
		sysPowerParam.notDeleted();
		sysPowerParam.setMenuCode(sysAppMenu.getMenuCode());
		boolean repeatCode = sysAppMenuService.repeat(sysPowerParam);
		if(repeatCode) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "APP菜单编码重复");
		}
		
		sysPowerParam.setMenuCode(null);
		sysPowerParam.setParentId(sysAppMenu.getParentId()); //一级下才不允许重复
		sysPowerParam.setMenuName(sysAppMenu.getMenuName());
		boolean repeatName = sysAppMenuService.repeat(sysPowerParam);
		if(repeatName) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "APP菜单名称重复");
		}
		
		sysAppMenu.setModifierName(currentUser.getName());
		sysAppMenu.setModifier(currentUser.getId());
		sysAppMenuService.saveUpdateAndDelete(sysAppMenu, OperateType.add);
		return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除sys_app_菜单<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除sys_app_菜单", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	sysAppMenuService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用sys_app_菜单<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用sys_app_菜单", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	sysAppMenuService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用sys_app_菜单<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用sys_app_菜单", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	sysAppMenuService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改sys_app_菜单 <br/>
     * @param sysAppMenu
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改sys_app_菜单", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute SysAppMenu sysAppMenu) {
    	AbstractSysUser currentUser = getCurrentUser();
		SysAppMenu sysPowerParam = new SysAppMenu();
		sysPowerParam.notDeleted();
		sysPowerParam.setId(sysAppMenu.getId());
		sysPowerParam.setMenuCode(sysAppMenu.getMenuCode());
		boolean repeatCode = sysAppMenuService.repeat(sysPowerParam);
		if(repeatCode) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "APP菜单编码重复");
		}
		
		sysPowerParam.setMenuCode(null);
		sysPowerParam.setParentId(sysAppMenu.getParentId()); //一级下才不允许重复
		sysPowerParam.setMenuName(sysAppMenu.getMenuName());
		boolean repeatName = sysAppMenuService.repeat(sysPowerParam);
		if(repeatName) {
			return ApiResponse.fail(ResultFlagType.REPEAT_DATA.getCode(), "APP菜单名称重复");
		}
		
		sysAppMenu.setModifierName(currentUser.getName());
		sysAppMenu.setModifier(currentUser.getId());
		sysAppMenuService.saveUpdateAndDelete(sysAppMenu, OperateType.edit);
		return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询sys_app_菜单<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询sys_app_菜单", response = SysAppMenu.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       SysAppMenu sysAppMenu = sysAppMenuService.selectById(id);
       if(null == sysAppMenu) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(sysAppMenu);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询sys_app_菜单 <br/>
     * @param sysAppMenuExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询sys_app_菜单",response = SysAppMenu.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute SysAppMenuExt sysAppMenuExt){
        sysAppMenuExt.notDeleted();
        PageVo page = getPage(sysAppMenuExt);
        int records = sysAppMenuService.countByExt(sysAppMenuExt);
        page.setRecords(records);
        if (records > 0) {
            List<SysAppMenu> sysAppMenus = sysAppMenuService.selectByExt(sysAppMenuExt);
            page.setRows(sysAppMenus);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
